package org.casper.netty.nettydemo;

import java.util.Date;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
/**
 * 2016年3月30日10:29:16
 * @author casper
 */
public class TimeServerHandler extends ChannelHandlerAdapter {
	/*
	 * 用于对网络事件进行读写操作
	 */
	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		ByteBuf buf = (ByteBuf) msg;
		byte[] req = new byte[buf.readableBytes()]; //获取缓冲区可读的字节数
		buf.readBytes(req);							//将缓冲区的字节数组复制到新建的byte数组中
		String body = new String(req,"UTF-8");
		System.out.println("the time server receive order:"+body);
		String currentTime = "QUERY ORDER TIME".equalsIgnoreCase(body)?new Date(System.currentTimeMillis()).toString():"BAD ORDER";
		ByteBuf resp = Unpooled.copiedBuffer(currentTime.getBytes());
		ctx.write(resp);							//netty只是将待发送的消息发送到缓冲数组当中
	}

	@Override
	public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
		ctx.flush();								//将缓冲区的消息的全部写到SocketChannel当中
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
		ctx.close();
	}
	
	
	
	
	

}
